<template>
  <div class="set-container">
    <div class="total-container">
      <div class="naviga">产品能力分析&nbsp;>  <span class="navigaActive">产品大盘</span></div>
      <div class="mainPage">
        <div class="summaryHeader">
        <span class="lightYellow">{{catagrayCount}}</span>个品类，<span class="lightYellow">{{productCount}}</span>个产品型号，其中<span class="lightYellow">{{onLine}}</span>个型号在售，<span class="lightYellow">{{offLine}}</span>个型号下市
        </div>
        <div class="itemContainer">
          <div class="itemTitle">
            <span>销售走势</span>
            <div class="pickerOption">
                <el-radio-group size="small" v-model="selectedMonth" @change="onSaleRangeChange">
                  <el-radio-button label="最近半年">最近半年</el-radio-button>
                  <el-radio-button label="最近3个月">最近3个月</el-radio-button>
                  <el-radio-button label="最近1个月">最近1个月</el-radio-button>
                </el-radio-group>
                <el-select size="small" v-model="selectedYear" placeholder="选择年份"
                           style="width: 156px" @change="onSaleRangeChange">
                  <el-option v-for="item in summaryYearRange" :key="item"
                             :label="item" :value="item">
                  </el-option>
                </el-select>
            </div>
          </div>
          <div id="saleSummaryChart" style="height: 300px"></div>
        </div>
        <div class="itemContainer">
          <div class="itemTitle white">
            <span style="color: #909399;">品类与产品型号销售数据</span>
            <div class="pickerOption">
                <el-radio-group v-model="yearsCopy" size="small" @change="onSaleDetailRangeChange">
                  <el-radio-button label="最近半年">最近半年</el-radio-button>
                  <el-radio-button label="最近3个月">最近3个月</el-radio-button>
                  <el-radio-button label="最近1个月">最近1个月</el-radio-button>
                </el-radio-group>
                <el-select v-model="selectedDetailYear" placeholder="选择年份" style="width: 156px"
                           size="small" @change="onSaleDetailRangeChange">
                  <el-option v-for="item in summaryDetailYearRange" :key="item" :label="item" :value="item"></el-option>
                </el-select>
            </div>
          </div>
          <div class="categroySale">
            <div class="itemTitle">
              <span>品类销售</span>
              <div class="pickerOption">
                <el-select v-model="categoryId" placeholder="分类" style="width: 156px;" size="small" @change="kindTopData">
                  <el-option v-for="item in catagoryData" :key="item.id" :label="item.categoryName" :value="item.categoryName">
                  </el-option>
                </el-select>
                <el-select v-model="sortType" placeholder="全部" style="width: 156px" size="small" @change="sortTopData">
                  <el-option label="销量从高到低" value="4"></el-option>
                  <el-option label="销量从低到高" value="3"></el-option>
                  <el-option label="销额从高到低" value="1"></el-option>
                  <el-option label="销额从低到高" value="2"></el-option>
                </el-select>
              </div>
            </div>
            <div class="catagoryList">
              <div v-for='item in sortedProducions' class="catagoryContainer" :key="`sortedProd${item.category}`">
                <catagoryItem v-bind="item" :timeRange="searchDate"  class="itempie" :category="item.category"  :startDate='detailStartDate' :endDate='detailEndDate'></catagoryItem>
              </div>
              <!--<div v-else>
                暂无数据
              </div>-->
            </div>
          </div>
          <div>
            <div class="itemTitle">
              <span>公司产品型号top</span>
            </div>
            <div class="borderLine">
              <el-table :data="productionRankListValue" size="mini" style="width: 100%"
                        :default-sort = "{prop: 'salesAnalysisProduct.saleCount', order: 'descending'}">
                <el-table-column
                  type="index"
                  label="排名"
                  width="80px">
                </el-table-column>
                <el-table-column
                  prop="salesAnalysisProduct.productCode"
                  label="产品型号">
                </el-table-column>
                <el-table-column
                  prop="salesAnalysisProduct.salesType"
                  label="销售类型">
                </el-table-column>
                <el-table-column
                  sortable
                  prop="salesAnalysisProduct.saleAmount"
                  :formatter="formatterPrice"
                  label="销售额(万元)">
                </el-table-column>
                <el-table-column
                  sortable
                  prop="salesAnalysisProduct.saleCount"
                  label="销售量(件)">
                </el-table-column>
                <el-table-column
                  label="销量在品类占比">
                  <template slot-scope="scope">
                    <span>{{ scope.row.salesAnalysisProduct.countCategoryRatio | formatPercent }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="销量在全产品占比">
                  <template slot-scope="scope">
                    <span>{{ scope.row.salesAnalysisProduct.countAllRatio | formatPercent }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="销额在品类占比">
                  <template slot-scope="scope">
                    <span>{{ scope.row.salesAnalysisProduct.amountCategoryRatio | formatPercent }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="销额在全产品占比">
                  <template slot-scope="scope">
                    <span>{{ scope.row.salesAnalysisProduct.amountAllRatio | formatPercent }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" class="buttonFont" @click="dialogVisible = true;fetchData(scope.row.salesAnalysisProduct.productCode,'S',searchDate)">销售详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
          <div>
            <div class="itemTitle">
              <span>公司新品</span>
            </div>
            <div class="borderLine">
              <el-table :data="newRankList" style="width: 100%" size="mini"
                        :default-sort = "{prop: 'salesAnalysisProduct.saleCount', order: 'descending'}">
                <el-table-column
                  type="index"
                  label="排名"
                  width="80px">
                </el-table-column>
                <el-table-column
                  prop="salesAnalysisProduct.productCode"
                  label="产品型号">
                </el-table-column>
                <el-table-column
                  prop="salesAnalysisProduct.salesType"
                  label="销售类型">
                </el-table-column>
                <el-table-column
                  sortable
                  prop="salesAnalysisProduct.saleAmount"
                  :formatter="formatterPrice"
                  label="销售额(万元)">
                </el-table-column>
                <el-table-column
                  sortable
                  prop="salesAnalysisProduct.saleCount"
                  label="销售量(件)">
                </el-table-column>
                <el-table-column
                  label="销量在品类占比">
                  <template slot-scope="scope">
                    <span>{{ scope.row.salesAnalysisProduct.countCategoryRatio | formatPercent }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="销量在全产品占比">
                  <template slot-scope="scope">
                    <span>{{ scope.row.salesAnalysisProduct.countAllRatio | formatPercent }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="销额在品类占比">
                  <template slot-scope="scope">
                    <span>{{ scope.row.salesAnalysisProduct.amountCategoryRatio | formatPercent }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="销额在全产品占比">
                  <template slot-scope="scope">
                    <span>{{ scope.row.salesAnalysisProduct.amountAllRatio | formatPercent }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" class="buttonFont" @click="dialogVisible = true;fetchData(scope.row.salesAnalysisProduct.productCode,'S',searchDate)">销售详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </div>
      <el-dialog class="dialogHeaderFont" title="详细信息" :visible.sync="dialogVisible" width="100%" top="8vh">
        <div>
          <div class="itemContainer">
            <div class="itemTitle">销售情况</div>
            <div id="saleDetailSummaryChartS" style="height: 300px"></div>
          </div>
          <div class="itemContainer" style="margin-bottom: 0">
            <div class="titleHeader space-between">
              <span style="font-weight: bold">销售渠道分布</span>
              <el-form :inline="true" class="demo-form-inline single-form-inline locationDetail pickerOption" size="small">
                <el-form-item label="地区">
                  <el-select v-model="country" placeholder="选择地区" @change="channelSel(searchDate)">
                    <el-option v-for="(item,index) in area" :key="index" :label="item" :value="item"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="省份">
                  <el-select v-model="province" placeholder="选择省份" @change="channelSel(searchDate)">
                    <el-option v-for="(item,index) in provinceList" :key="index" :label="item" :value="item" ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="城市">
                  <el-select v-model="city" placeholder="选择城市" @change="channelSel(searchDate)">
                    <el-option v-for="(item,index) in cityLists" :key="index" :label="item" :value="item" ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="门店">
                  <el-select v-model="shop" placeholder="选择门店" @change="channelSel(searchDate)">
                    <el-option v-for="(item,index) in shopLists" :key="index" :label="item" :value="item" ></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
            <div id="salePointChartS" style="height: 300px"></div>
          </div>
          <div v-if="shopIsAll" class="priceDetail">
              <div class="">
                <div class="itemTitle">
                  <span>终端销售统计</span>
                </div>
                <el-table :data="priceTableData" style="width: 100%" size="mini">
                  <el-table-column
                    prop="shopName"
                    label="门店名称">
                  </el-table-column>
                  <el-table-column
                    sortable
                    prop="amountCount"
                    label="销售额(万元)">
                  </el-table-column>
                  <el-table-column
                    sortable
                    prop="salesCount"
                    label="销售量(万件)">
                  </el-table-column>
                  <el-table-column
                    sortable
                    prop="zhanBi"
                    label="销量在全品类中占比">
                  </el-table-column>
                </el-table>
              </div>
              <div class="">
                <div class="itemTitle">
                  <span>渠道表现趋势</span>
                </div>
                <div id="salePriceChartS" style="height: 300px"></div>
              </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import catagoryItem from './catagoryItem'
  import * as opreate from 'api/getData'
  import mixins from 'utils/mixin'
  let mapMineSet = new Map([
    ['近一年', { value: 4, valSet: 1, label: '近一年', mUtilSet: 12 }],
    ['最近半年', { value: 3, valSet: 6, label: '最近半年', mUtilSet: 6, show: true }],
    ['最近3个月', { value: 2, valSet: 3, label: '最近3个月', mUtilSet: 3, show: true }],
    ['最近1个月', { value: 1, valSet: 0, label: '最近1个月', mUtilSet: 1, show: true }]
  ])

  export default {
    name: "totalPanel",
    mixins:[mixins.mixin],
    components: {
      catagoryItem
    },
    data() {
      const currentYear = new Date().getFullYear()
      const currentMonth = new Date().format('MM')
      const startDate = `${currentYear - 1}-${currentMonth}`
      const endDate = `${currentYear}-${currentMonth}`
      return {
        shopIsAll: true,
        yearsCopy:'',
        catagrayCount: '',
        productCount: '',
        onLine: '',
        offLine: '',
        currentYear,
        dataStartMonth: '',
        dataEndMonth: '',
        startDate,
        detailStartDate: startDate,
        detailEndDate: endDate,
        endDate,
        saleSummary: [],
        selectedMonth: '',
        selectedYear: '近一年',
        selectedDetailYear: '近一年',
        timeRange:'近一年',
        summaryYearRange: ['近一年'],
        summaryDetailYearRange: ['近一年'],
        sortedList: [],
        productionSaleDetail: [],
        productionRankList: { countAsc: [] },
        productionRankListValue: [],
        newRankList: [],
        categoryId: '全部品类',
        sortType: '4',
        pickerOptions2: {},
        catagoryData: [],
        dialogVisible: false,
        data: [],
        saleInfo: [],
        priceChartData: [],
        priceTableData: [],
        sortTopDataValue: "1",
        sortedProducions:[],
        num:'',
        salePointChart:[],
        arr:['salesAnalysisProduct.saleCount','salesAnalysisProduct.countAllRatio']
      }
    },
    computed:{
      searchDate:{
        set:function(){},
        get:function(){
          let tempSet = this.yearsCopy || this.selectedDetailYear;
          tempSet = mapMineSet.get(tempSet) || { mUtilSet: tempSet }
          return tempSet.mUtilSet
        }
      }
    },
    mounted(){
      this.getSumaryNum()
      this.getDataSet(4,'',4)
      this.getSaleSummary(1)
      this.getSaleDetail(4,4)
      this.getAvailableRange()
      opreate.getCategoryName().then(res => {
        this.catagoryData = res.data || []
      })
    },
    methods: {
      formatterPrice(row, column){
        return parseFloat((row.salesAnalysisProduct.saleAmount || 0)/10000).toFixed(2)
      },
      getSumaryNum(){
        opreate.productNumber().then(res => {
          let { totalCategory, totalProductCode, onlineSaleCount, offlineSaleCount  } = res.data || {}
          this.catagrayCount = totalCategory
          this.productCount = totalProductCode
          this.onLine = onlineSaleCount
          this.offLine = offlineSaleCount
        })
      },
      getDataSet(num,category,sort) {
        opreate.getSaleCateGroup({ num,category,sort }).then(res => {
          this.sortedProducions = res.data || []
        })
      },
      getSaleSummary(num) {
        opreate.salesTrend(num).then((res) => {
          this.saleSummary = res.data || []
          let myChart = this.$echarts.init(document.getElementById('saleSummaryChart'));
          let optionSet = {   // 指定图表的配置项和数据
            legend: {
              data:['销售量','销售额'],
              right:'20'
            },
            xAxis: {
              data: this.saleSummary.map(item => item.dateTime)
            },
            tooltip:{
              show:true,
              trigger: 'axis'
            },
            yAxis: [{
              name: '销售量（件）',
              type: 'value'
            }, {
              name: '销售额（万元）',
              type: 'value'
            }],
            series: [{
              name: '销售量',
              type: 'line',
              yAxisIndex: 0,
              smooth:true,
              itemStyle: {
                color: '#B0ACEC'
              },
              data: this.saleSummary.map(item => (item.salesCount))
            }, {
              name: '销售额',
              type: 'line',
              smooth:true,
              itemStyle: {
                color: '#9DD6F9'
              },
              yAxisIndex: 1,
              data: this.saleSummary.map(item => (item.salesAmount/10000).toFixed(2))
            }]
          }
          myChart.setOption(optionSet) // 使用刚指定的配置项和数据显示图表
        })
      },
      onSaleRangeChange(value) {
        let tempSet = mapMineSet.get(value) || { valSet: value, label:value }
        this.getSaleSummary(tempSet.valSet)
        if(tempSet.show){
          this.selectedMonth = tempSet.label
          this.selectedYear = ''
        }else {
          this.selectedMonth = ''
          this.selectedYear = tempSet.label
        }
      },
      onSaleDetailRangeChange(value) {
        this.categoryId = '全部品类'
        this.sortType = '4'
        this.timeRange = value
        let tempSet = mapMineSet.get(value) || { value: value, label:value }
        this.getSaleDetail(tempSet.value,4)
        this.getDataSet(tempSet.value,this.categoryId,this.sortType)
        if(tempSet.show){
          this.yearsCopy = tempSet.label
          this.selectedDetailYear = ''
        }else {
          this.yearsCopy = ''
          this.selectedDetailYear = tempSet.label
        }
      },
      getSaleDetail(num,sort) {
        Promise.all([opreate.productTop(num,sort),opreate.newProductList(num,sort)]).then(res => {
          this.productionRankListValue = res[0].data
          this.newRankList = res[1].data
        })
      },
      getAvailableRange() {
          let current = new Date().getFullYear()
          let years = [current, current-1, current-2]
          this.summaryYearRange = [ '近一年', ...years ]
          this.summaryDetailYearRange = [ '近一年', ...years ]
      },
      sortTopData(newVal) {
        let tempSet = '' != this.yearsCopy ? mapMineSet.get(this.yearsCopy) : (mapMineSet.get(this.selectedDetailYear) || { value: this.selectedDetailYear, label: '' })
        this.getDataSet(tempSet.value, this.categoryId, newVal)
      },
      kindTopData(newVal){
        let tempSet = '' != this.yearsCopy ? mapMineSet.get(this.yearsCopy) : (mapMineSet.get(this.selectedDetailYear) || { value: this.selectedDetailYear, label: '' })
        this.getDataSet(tempSet.value, newVal, this.sortType)
      }
    },
    watch:{
      dialogVisible(newVal){
        let initEcharts = document.getElementById("salePriceChartS")
        let initRender = initEcharts ? this.$echarts.init(initEcharts) : null
        initRender && initRender.clear()
      },
      shop(newVal){
        if("全部" == newVal){
          this.priceTableData = []
          this.shopIsAll = true
        }else {
          this.shopIsAll = false
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  .mainPage {
    background-color: #E8EEF4
  }
  .itemContainer {
    background-color: white;
    padding: 10px;
    margin: 0 10px 10px;
  }
  .itemTitle {
    background-color: #E8EEF4;
    height: 40px;
    padding: 0px 12px;
    line-height: 40px;
    display: flex;
    justify-content: space-between;
    font-weight: bold;
  }
  .itemTitle.white {
    background-color: white;
  }
  .itemTitle div{
    font-weight: bold;
  }
  .pickerOption {
    display: flex;
    align-items: center;
  }
  .purple {
    color: #B0ACEC
  }
  .lightBlue {
    color: #9DD6F9
  }
  .catagoryList {
    display: flex;
    flex-wrap: wrap;
  }
  .catagoryContainer {
    width: 25%;
    flex-basis: 25%;
    flex-grow: 0;
    flex-shrink: 0;
  }
  .categroySale{
    margin-bottom: 10px;
  }
  .itempie {
    margin: 10px;
    border: 1px solid #EEEEEE;
    border-radius: 10px;
  }
  .priceDetail {
    display: flex;
    background-color: #fff;
    padding: 10px;
    > div {
      flex: 1;
      flex-basis: 50%;
      margin: 10px;
    }
  }
</style>
